<template>
  <div>
    <top-bar></top-bar>
    <left-bar :datas='data'></left-bar>
    <div class="main">
      <div class="main-mains">
        <div class="main-content">
          <div class="main-mains-top">
            编辑资讯文章<el-button
              size="mini"
              type="primary"
              @click="goBack"
              class="goBack"
            >返回</el-button>
          </div>
          <div class="editItem" v-if="urlPoints == 1">
            <div class="group1 clear">
              <span class="leftTitle">*所属项目</span>
              <div class="rightContent">
                <el-select
                  v-model="projectId"
                  :disabled="urlType == 'againEdit'"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in projectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div class="editItem">
            <div class="group1 clear">
              <span class="leftTitle">*资讯标题</span>
              <div class="rightContent lgRightContent">
                <el-input
                  placeholder=""
                  v-model.trim="articleTitle"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="editItem" v-if="urlPoints == 0">
            <div class="group1 clear">
              <span class="leftTitle">*分类</span>
              <div class="rightContent">
                <el-select
                  v-model="category_id"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in categoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div class="editItem">
            <div class="group1 clear">
              <span class="leftTitle">*作者</span>
              <div class="rightContent lgRightContent">
                <el-input
                  placeholder=""
                  v-model.trim="article_source"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="editItem"  v-if="urlPoints == 1">
            <div class="group1 clear">
              <span class="leftTitle">*请选择浏览对象</span>
              <div class="rightContent pointsInput">
                <li v-for="(item,index) in roleList" :key="index">
                   <el-checkbox v-model="checkIdList" :label="item.id" @change="changeValue()">{{item.role_name}}</el-checkbox>
                   <span class="sonSpan">浏览发放积分</span>
                   <el-input v-model="item.read_budget" type="number"  @blur="changeValue()"></el-input>
                   <span class="sonSpan">浏览每人可得积分</span>
                   <el-input v-model="item.read_score" type="number"></el-input>
                   <span class="sonSpan" v-if="urlType == 'againEdit'">已用:{{item.read_used}}</span>
                </li>
                <div class="totalPoints">浏览总发放积分:<span> {{totalPoints}}</span></div>
              </div>
            </div>
          </div>
          <div class="editItem">
            <div class="group1 clear">
              <span class="leftTitle">文章封面</span>
              <div class="rightContent">
                <el-upload
                  :action="uploadImgUrl"
                  :on-success="uploadImgSuccess"
                  list-type="picture-card"
                  :data="uploadData"
                  name="img"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :file-list="img_url"
                  :headers="uploadHeader"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </div>
          </div>
          <div class="editItem">
            <div class="group1 clear">
              <span class="leftTitle">*文章内容</span>
              <div class="rightContent lgRightContent">
                <script
                  id="productDescriptionContainer"
                  name="productDescriptionContainer"
                  type="text/plain"
                ></script>
              </div>
            </div>
          </div>
          <div class="operationButtom">
            <el-button
              round
              size="medium"
              @click="goBack"
            >取消</el-button>
            <el-button
              round
              size="medium"
              v-if="urlPoints == 0"
              type="warning"
              @click="saveArticle(2)"
            >保存草稿</el-button>
            <el-button
              round
              size="medium"
              v-if="urlType == 'againEdit'"
              type="danger"
              @click="saveArticle(0)"
            >下架</el-button>
            <el-button
              round
              size="medium"
              type="success"
              @click="saveArticle(1)"
            >发布</el-button>
          </div>
        </div>
      </div>
      <!-- 预览图片 -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
  </div>
</template>


<script>
import leftBar from "@/components/leftBar";
import topBar from "@/components/topBar";
import newsMan from "@/api/newsMan";
import pubilc from "@/api/pubilc";
import store from "../store";
export default {
  components: {
    leftBar,
    topBar
  },
  data() {
    return {
      data: "newsman",
      newImgUrl: [],
      img_url: [],
      uploadImgUrl: "http://dev.cso.miotchina.net/adm/upload",
      projectId: "",
      projectOptions: [],
      category_id: "",
      categoryOptions: [],
      uploadData: {
        type: 11,
        filename: "img"
      },
      uploadHeader: {
        Authorization: "Bearer " + store.state.access_token
      },
      read_score: "",
      read_budget: "",
      articleTitle: "",
      article_source: "",
      urlPoints: "",
      urlType: "",
      urlArticleId: "",
      dialogVisible:false,
      dialogImageUrl:"",
      roleList:[
        {
          id:1,
          role_name:"专科医生",
          read_budget:"",
          read_score:"",
          read_used:""
        },
        {
          id:2,
          role_name:"全科医生",
          read_budget:"",
          read_score:"",
          read_used:""
        },
        {
          id:3,
          role_name:"医疗相关从业者",
          read_budget:"",
          read_score:"",
          read_used:""
        },
        {
          id:4,
          role_name:"药店经营人员",
          read_budget:"",
          read_score:"",
          read_used:""
        },
        {
          id:6,
          role_name:"医业业务代表",
          read_budget:"",
          read_score:"",
          read_used:""
        },
        {
          id:7,
          role_name:"医学生",
          read_budget:"",
          read_score:"",
          read_used:""
        }
      ],
      checkIdList:[],
      totalPoints:0
    };
  },
  mounted() {
    this.urlPoints = this.getUrlParam("points");
    this.urlType = this.getUrlParam("type");
    this.urlArticleId = this.getUrlParam("articleId");
    if (this.urlType == "againEdit") {
      if(this.urlPoints == 1){
         this.getPointsNewDetail(this.urlArticleId);
      }
      else if(this.urlPoints == 0){
         this.getNoPointsNewDetail(this.urlArticleId);
      }
    }
    UE.delEditor("productDescriptionContainer");
    this.ueditorFun(); //初始化编辑器
    this.getCategory();
    this.getProject();
  },
  methods: {
    //编辑器函数
    ueditorFun() {
      let _this = this;
      this.productDescriptionue = UE.getEditor("productDescriptionContainer", {
        initialFrameWidth: 950,
        initialFrameHeight: 500,
        autoHeightEnabled: false,
        zIndex: 0,
        maximumWords: 10000, //允许的最大字符数
        saveInterval: 999999 //自动保存间隔时间，单位ms
      });
      this.productDescriptionue.ready(function() {
        _this.productDescriptionue.setContent(_this.productDescHtml);
      });
    },
    changeValue(index){
      let total = 0;
      for(let i=0; i<this.roleList.length; i++){
        if(this.checkIdList.indexOf(this.roleList[i].id) != -1){
            total += Number(this.roleList[i].read_budget);
        }
      }
      this.totalPoints = total;
    },
    //获取文章详情
    getPointsNewDetail(id) {
      let options;
      let _this = this;
      options = {
        article_id: id
      };
      newsMan.getPointsNewDetail(options).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          let img_url = [];
          _this.category_id = data.categorys.id;
          _this.projectId = data.spid;
          _this.productDescHtml = data.content;
          _this.ueditorFun();
          _this.articleTitle = data.title;
          _this.article_source = data.article_source;
          _this.read_score = data.read_score;
          _this.read_budget = data.read_budget;
          if (data.img_url.length > 0) {
            for (let i = 0; i < data.img_url.length; i++) {
              let imgeSplit = data.img_url[i].split("/");
              let imgName = imgeSplit[imgeSplit.length - 1];
              img_url.push({
                name: imgName,
                url: data.img_url[i]
              });
            }
          }
          _this.img_url = img_url;
          _this.newImgUrl = img_url;
          for(let i=0; i<_this.roleList.length; i++){
             for(let j=0; j<data.score_rule.length; j++){
               if(_this.roleList[i].id === data.score_rule[j].role){
                 _this.roleList[i].read_score = data.score_rule[j].read_score;
                 _this.roleList[i].read_budget = data.score_rule[j].read_budget;
                 _this.roleList[i].read_used = data.score_rule[j].read_used;
                 _this.totalPoints +=  data.score_rule[j].read_budget;
                 _this.checkIdList.push(data.score_rule[j].role)
               }
             }
          }
        }
      });
    },
    //获取无积分文章详情
    getNoPointsNewDetail(id){
      let options;
      let _this = this;
      options = {
        article_id: id
      };
      newsMan.getNoPointsNewDetail(options).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          let img_url = [];
          _this.category_id = data.categorys.id;
          _this.projectId = data.spid;
          _this.productDescHtml = data.content;
          _this.ueditorFun();
          _this.articleTitle = data.title;
          _this.article_source = data.article_source;
          if (data.img_url.length > 0) {
            for (let i = 0; i < data.img_url.length; i++) {
              let imgeSplit = data.img_url[i].split("/");
              let imgName = imgeSplit[imgeSplit.length - 1];
              img_url.push({
                name: imgName,
                url: data.img_url[i]
              });
            }
          }
          _this.img_url = img_url;
          _this.newImgUrl = img_url;
        }
      });
    },
    //保存文章
    saveArticle(type) {
      let _this = this;
      let options;
      let img_url = [];
      this.productDescHtml = this.productDescriptionue.getContent();
      if (
        this.articleTitle === "" ||
        this.productDescHtml === "" ||
        this.newImgUrl.length <= 0 ||
        this.article_source === ""
      ) {
        this.messageAlert("请填写完整信息");
        return;
      }
      for (let i = 0; i < this.newImgUrl.length; i++) {
        if (this.newImgUrl[i].url.indexOf("blob:") != -1) {
          img_url.push(this.newImgUrl[i].response.data.file.path);
        } else {
          img_url.push(this.newImgUrl[i].name);
        }
      }
      img_url = JSON.stringify(img_url);
      if(this.urlPoints == 1){
        //有积分的情况：
        let score_rule = [];
        if(this.projectId === ""){
          this.messageAlert("请选择所属项目！");
          return;
        }
        if (Number(this.read_budget) < Number(this.read_score)) {
          this.messageAlert("总发放积分不能小于每人浏览得到的积分！");
          return;
        }
        for(let i=0; i<this.roleList.length; i++){
          if(this.checkIdList.indexOf(this.roleList[i].id) != -1){
            if(this.roleList[i].read_score === "" || this.roleList[i].read_budget === ""){
              this.messageAlert("勾选浏览对象后 ‘浏览发放积分’ 或 ‘浏览每人可得积分’ 不能为空！");
              return;
            }
            score_rule.push({
              role:this.roleList[i].id,
              read_score:this.roleList[i].read_score,
              read_budget:this.roleList[i].read_budget,
              surveys_score:0,
              surveys_budget:0
            })
          }
        }
        options = {
          check_status: type,
          title: this.articleTitle,
          content: this.productDescHtml,
          category_id: "25",
          author: this.article_source,
          img_url: img_url,
          score_rule: JSON.stringify(score_rule),
          read_score:1,
          read_budget:1
        };
      }
      else if(this.urlPoints == 0){
         //无积分的情况：
         if(this.category_id === ""){
          this.messageAlert("请选择分类！");
          return;
        }
        options = {
          check_status: type,
          title: this.articleTitle,
          content: this.productDescHtml,
          category_id: this.category_id,
          author: this.article_source,
          img_url: img_url,
          read_score:0,
          read_budget:0
        };
      }
      if (this.urlType == "againEdit") {
        // 编辑资讯:
        options = Object.assign(options, { article_id: this.urlArticleId});
      } else if (this.urlType == "add" && this.urlPoints == 1) {
        // 新增资讯
        options = Object.assign(options, { spid: this.projectId });
      }
      newsMan.saveArticle(options, this.urlType).then(function(res) {
        if (res.code == 1) {
          _this.successfulAlert("操作成功");
          history.go(-1);
        }
      });
    },
    //获取分类
    getCategory() {
      let _this = this;
      this.categoryOptions = [];
      let options;
      options = {
        name: "",
        category_id: ""
      };
      newsMan.getCategory(options).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          for (let i = 0; i < data.length; i++) {
            _this.categoryOptions.push({
              value: data[i].category_id,
              label: data[i].name
            });
          }
        }
      });
    },
    //获取项目
    getProject() {
      let _this = this;
      this.projectOptions = [];
      let options;
      options = {
        spid: "",
        topic: ""
      };
      newsMan.getProject(options).then(function(res) {
        let data = res.data;
        if (res.code == 1) {
          for (let i = 0; i < data.models.length; i++) {
            _this.projectOptions.push({
              value: data.models[i].id,
              label: data.models[i].topic
            });
          }
        }
      });
    },
    //上传图片成功
    uploadImgSuccess(response, file, fileList) {
      this.newImgUrl = fileList;
    },
    //删除图片
    handleRemove(file, fileList) {
      this.newImgUrl = fileList;
    },
    //预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //返回
    goBack() {
      history.go(-1);
    },
    //获取地址栏参数
    getUrlParam(paraName) {
      var url = document.location.toString();
      var arrObj = url.split("?");
      if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;
        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split("=");
          if (arr != null && arr[0] == paraName) {
            return arr[1];
          }
        }
        return "";
      } else {
        return "";
      }
    },
    //错误弹窗
    messageAlert(msg) {
      this.$message.error(msg);
    },
    //成功弹窗
    successfulAlert(msg) {
      this.$message({
        message: msg,
        type: "success"
      });
    }
  }
};
</script>

<style lang="less">
.editItem {
  padding: 20px 20px;
  .group1 {
    .leftTitle {
      float: left;
      height: 36px;
      line-height: 36px;
      font-size: 14px;
      color: #2d2d2d;
      min-width: 110px;
      margin-right: 10px;
    }
    .rightContent {
      float: left;
      .tip1 {
        float: left;
        color: #999;
        font-size: 12px;
      }
    }
    .lgRightContent {
      width: 40%;
    }
    .pointsInput{
      li{
        border-bottom: 1px solid #eaeaea;
        padding: 5px 0;
        .el-checkbox{
          width: 150px;
          margin-right: 0;
        }
        .sonSpan{
          width: 200px;
          display: inline-block;
          text-align: right;
          color: #f56c6c;
          font-size: 14px;
          margin-right: 10px;
        }
        .el-input{
          width: 100px;
          .el-input__inner, .el-input__inner:hover{
            padding: 0 0 0 10px;
          }
        }
      }
      .totalPoints{
        background-color: #d7d7d7;
        text-align: right;
        padding: 10px;
        span{
          color: #f56c6c;
        }
      }
    }
  }
}
.operationButtom {
  text-align: center;
  height: 100px;
  margin-top: 30px;
}
</style>
